package com.itcncp.wechat.app.mini.controller;
import com.itcncp.common.base.BaseController;
import com.itcncp.common.model.OrderCodeType;
import com.itcncp.common.util.DateUtils;
import com.itcncp.common.util.OrderUtils;
import com.itcncp.common.util.StringUtil;
import com.itcncp.wechat.app.common.constant.ApiConstant;
import com.itcncp.wechat.app.common.constant.ApiResult;
import com.itcncp.wechat.app.common.constant.ApiResultConstant;
import com.itcncp.wechat.app.dao.model.*;
import com.itcncp.wechat.app.rpc.api.*;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 *
 */
@Controller
@RequestMapping("/transJnl")
@Api(tags = "通行订单记录",value = "通行记录", description = "通行记录",
        produces = "transJnl",consumes = "transJnl",basePath = "/transJnl")
class TransJnlController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger( TransJnlController.class);

    @Autowired
    private ItcsTransJnlService itcsTransJnlService;

    @Autowired
    private ItcsExitWhitelistRgtService itcsExitWhitelistRgtService;

    @Autowired
    private ItcsPlazaInfoService itcsPlazaInfoService;

    @Autowired
    private UserCarInfoService userCarInfoService;

    @Autowired
    private ItcsTerminalInfoService itcsTerminalInfoService;

    @Autowired
    private UserAccountInfoService userAccountInfoService;

    @Autowired
    private UserAccountOpJnlService userAccountOpJnlService;
    /**
     *  清空白名单
     */
    @ResponseBody
    @ApiOperation(value="清空白名单",notes="强制下发白名单，如果用户多次发起白名单车牌识别后，无订单响应，可调用此接口后再下发白名单请求")
    @RequestMapping(value = "/clearExitWhitelist", method = RequestMethod.POST)
    @ApiImplicitParams( value = {
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "Long", required = true, value = "用户ID")
    })
    public Object ClearExitWhitelist(HttpServletRequest request,
                                  @RequestParam(required = false, defaultValue = "0", value = "userId") Long userId){

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        ItcsExitWhitelistRgtExample itcsExitWhitelistRgtExample = new ItcsExitWhitelistRgtExample();
        itcsExitWhitelistRgtExample.createCriteria()
                .andUserIdEqualTo(userId);

        itcsExitWhitelistRgtService.deleteByExample(itcsExitWhitelistRgtExample);

        return  new ApiResult( ApiResultConstant.SUCCESS);
    }

    /**
     *  清空白名单
     */
    @ResponseBody
    @ApiOperation(value="测试接口，模仿前端车牌已识别",notes="")
    @RequestMapping(value = "/demoPlate", method = RequestMethod.POST)
    @ApiImplicitParams( value = {
            @ApiImplicitParam(paramType = "query", name = "plate", dataType = "String", required = true, value = "车牌号")
    })
    public Object ClearExitWhitelist(HttpServletRequest request,
                                     @RequestParam(required = false, defaultValue = "0", value = "plate") String plate){

        ItcsTransJnl itcsTransJnl = new ItcsTransJnl();
        itcsTransJnl.seteTollPlazaId("15");
        itcsTransJnl.setTollFare(new BigDecimal("1"));
        itcsTransJnl.setCreateTime(new Date());
        itcsTransJnl.setPayState(new Byte("1"));
        itcsTransJnl.setCarPlate(plate);
        itcsTransJnl.setPayTime(new Date());
        itcsTransJnl.setTollTime(new Date());
        itcsTransJnl.setTransNo(OrderUtils.getOrderNo("G"+OrderCodeType.CASHIN_NO.toString()));
        itcsTransJnlService.insertSelective(itcsTransJnl);

        return  new ApiResult( ApiResultConstant.SUCCESS);
    }




    /**
     * 发起出口白名单
     * @return
     */
    @ResponseBody
    @ApiOperation(value="发起出口白名单",notes="")
    @RequestMapping(value = "/sendExitWhitelist", method = RequestMethod.POST)
    @ApiImplicitParams( value = {
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "Long", required = true, value = "用户ID"),
            @ApiImplicitParam(paramType = "query", name = "tollstationId", dataType = "String", required = true, value = "收费广场Id")
    })
    public Object sendExitWhitelist(HttpServletRequest request,
                                      @RequestParam(required = true, defaultValue = "0", value = "userId") Long userId,
                                      @RequestParam(required = true, defaultValue = "", value = "tollstationId") String tollstationId ){

        try {

            //用户id验证
            if(userId<=0){
                return new ApiResult( ApiResultConstant.APP_ILLEGAL);
            }

            //用户收费站Id
            if(StringUtils.isBlank(tollstationId)){
                return new ApiResult( ApiResultConstant.APP_ILLEGAL);
            }
            UserCarInfoExample userCarInfoExample = new UserCarInfoExample();
            userCarInfoExample.createCriteria().andIsCheckEqualTo(new Byte("2"))
                    .andDelEqualTo(new Byte("2"))
                    .andUserIdEqualTo(userId);
            //查询用户未删除且审核过的车牌信息
            List<UserCarInfo> listPlate = userCarInfoService.selectByExample(userCarInfoExample);

            if (listPlate.size() < 1) {
                LOGGER.error("2005 发起出口白名单", "找不到用户，x`：userid" + userId);
                return new ApiResult(ApiResultConstant.APP_PLATE_NOT_EXIST);
            }

            // 3、tollstation收费站找所有盒子
            ItcsTerminalInfo terminalInfo = new ItcsTerminalInfo();
            terminalInfo.setTollPlazaId(tollstationId);
            ItcsTerminalInfoExample itcsTerminalInfoExample = new ItcsTerminalInfoExample();
            itcsTerminalInfoExample.createCriteria().andTollPlazaIdEqualTo(tollstationId);

            List<ItcsTerminalInfo> terminals = itcsTerminalInfoService.selectByExample(
                    itcsTerminalInfoExample
            );

            if(null == terminals){
                return new ApiResult(ApiResultConstant.APP_NOT_DEVICE);
            }

            ItcsExitWhitelistRgtExample itcsExitWhitelistRgtExample
                    = new ItcsExitWhitelistRgtExample();
            itcsExitWhitelistRgtExample.createCriteria().andUserIdEqualTo(userId);
            // 4、通过USERID，清空旧的USERID、盒子
            itcsExitWhitelistRgtService.deleteByExample( itcsExitWhitelistRgtExample  );
            // 5、记录是否在线，新存储USERID、车牌、盒子等信息为新白名单，存储入库
            String carPlateStr = "";
            String plateColorStr = "";
            String carClassStr = "";
            for (int i = 0; i < listPlate.size(); i++) {
                // 创建白名单
                ItcsExitWhitelistRgt whitelist = new ItcsExitWhitelistRgt();
                // whitelist.setState(0);
                whitelist.setCreateTime(new Date());
                // whitelist.set
                whitelist.setUserId(userId);
                UserCarInfo plate = listPlate.get(i);// 车牌号
                whitelist.setCarPlate(plate.getPlate());
                whitelist.setStationId(tollstationId);
                Byte palteColor = plate.getPlateColor();
                whitelist.setPlateColor(palteColor == null ? null : palteColor.byteValue());// 车牌颜色??
                Byte carClass = plate.getCarClass();
                whitelist.setCarClass(carClass == null ? null : carClass.byteValue());// 车型??
                itcsExitWhitelistRgtService.insert(whitelist);

                if (i > 0) {
                    carPlateStr += "," + plate.getPlate();
                    plateColorStr += "," + plate.getPlateColor();
                    carClassStr += "," + plate.getCarClass();
                } else {
                    carPlateStr = plate.getPlate();
                    plateColorStr = String.valueOf(plate.getPlateColor());
                    carClassStr = String.valueOf(plate.getCarClass());
                }
            }
//            // 将车牌下发给盒子
//            logger.info(LogUtils.build("2005", "发起出口白名单", "carPlateStr:" + carPlateStr + ",plateColorStr:"
//                    + plateColorStr + ",carClassStr:" + carClassStr + ",tollstationId:" + tollstationId));
//
//            for (int i = 0; i < terminals.size(); i++) {
//                TerminalInfo terminal = terminals.get(i);
//                BoxResponse response2005 = BoxResUtils.build2005(String.valueOf(terminal.getTerminalNo()),
//                        String.valueOf(listPlate.size()), carPlateStr, plateColorStr, carClassStr);
//                sendBoxSocket.pubsubRes2BoxServer(response2005);
//            }
        } catch (Exception e) {
//            logger.error(LogUtils.build("2005", "发起出口白名单", "处理异常"), e);
            return new ApiResult( ApiResultConstant.FAILED);
        }

        return new ApiResult( ApiResultConstant.SUCCESS);
    }


    /**
     *  获取支付订单信息
     */
    @ResponseBody
    @ApiOperation(value="获取支付订单信息",notes="获取用户在30分钟内的订单信息")
    @RequestMapping(value = "/getOrderNo", method = RequestMethod.POST)
    @ApiImplicitParams( value = {
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "Long", required = true, value = "用户ID")
    })
    public Object getOrderNo(HttpServletRequest request,
                      @RequestParam(required = false, defaultValue = "0", value = "userId") Long userId){

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        ItcsTransJnl itcsTransJnl = itcsTransJnlService.getByWxitWhitelistUserId(userId);


        //填充收费站名称
        if(null != itcsTransJnl){
            List<ItcsPlazaInfo> itcsPlazaInfos = itcsPlazaInfoService.selectOwnerPlazaByCache(DateUtils.dateFormatNow( "YYYYMMDDHH" ));

            for (ItcsPlazaInfo itcsPlazaInfo:itcsPlazaInfos){
                if(null != itcsTransJnl.getiTollPlazaId() &&  itcsTransJnl.getiTollPlazaId().equals(itcsPlazaInfo.getTollPlazaId())){
                    itcsTransJnl.setiTollPlazaName(itcsPlazaInfo.getName());
                }
                if(null != itcsTransJnl.geteTollPlazaId() &&  itcsTransJnl.geteTollPlazaId().equals(itcsPlazaInfo.getTollPlazaId())){
                    itcsTransJnl.seteTollPlazaName(itcsPlazaInfo.getName());
                }
            }
        }

        return  new ApiResult( ApiResultConstant.SUCCESS,itcsTransJnl);
    }

    /**
     *  支付通行费订单
     */
    @ResponseBody
    @ApiOperation(value="支付通行费订单",notes="")
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @ApiImplicitParams( value = {
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "Long", required = true, value = "用户ID"),
            @ApiImplicitParam(paramType = "query", name = "traderecordsId", dataType = "String", required = true, value = "订单号")
    })
    public Object pay(HttpServletRequest request,
                      @RequestParam(required = false, defaultValue = "0", value = "userId") Long userId,
                      @RequestParam(required = false, defaultValue = "0", value = "traderecordsId") String traderecordsId){

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }


        //订单号不能为空
        if(StringUtils.isBlank(traderecordsId)){
            return new ApiResult( ApiResultConstant.APP_ORDER_FAILS);
        }

        ItcsTransJnlExample itcsTransJnlExample = new ItcsTransJnlExample();
        itcsTransJnlExample.createCriteria().andTransNoEqualTo(traderecordsId);
        ItcsTransJnl traderecords = itcsTransJnlService.selectFirstByExample(
                itcsTransJnlExample
        );

        // 根据订单ID查询itcs_trans_jnl,获取支付状态 1待支付 2支付成功 3支付失败 4支付异常,
        // Map<String, Object> trans = transJournalMapper.selectByPlayerId((String)
        // paramMap.get("traderecordsId"));
        if (traderecords == null) {// 查不到数据，返回相关信息
            return new ApiResult( ApiResultConstant.APP_ORDER_FAILS);
        }

        // TODO 改成常量
        if (traderecords.getPayState() == 2 || traderecords.getPayState() == 5) {// 支付成功
            return new ApiResult( ApiResultConstant.APP_ORDER_PAYMENT);

        }

        // 判断金额,如果账户余额<通行费额应付金额,提示余额不足，否则进行扣款交易
        UserAccountInfo userInfo = userAccountInfoService.selectByPrimaryKey(userId);
        if (userInfo == null) {
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        BigDecimal oldBalance = (BigDecimal) userInfo.getAccountBalance();// 账户余额
        BigDecimal balance = (BigDecimal) traderecords.getTollFare();// 通行费应付金额
        int amountFlag = oldBalance.compareTo(balance);
        // System.out.println("userAmount==" + oldBalance + "tollFareAmount" + balance +
        // "amountFlag" + amountFlag);
        if (amountFlag == 0 || amountFlag == 1) {// 账户余额大于或等于通行费应付金额
            traderecords.setPayerId(new Byte("1"));
            traderecords.setPayState(new Byte("2"));// 更新订单状态
            traderecords.setUserId(userInfo.getUserId());
            itcsTransJnlService.updateByPrimaryKeySelective(traderecords);
            // TransJournal.pay;
            // =============================账户历史变动表================================
            // 将数据插入的账户历史变动表中?????????,需记录到记录表串
            BigDecimal endBalance = oldBalance.subtract(balance);// 计算账户余额

            UserAccountOpJnl userAccountOpHis = new UserAccountOpJnl();
            userAccountOpHis.setTransNo(traderecordsId);
            userAccountOpHis.setTransTimestamp(new Date());
            userAccountOpHis.setUserId(userInfo.getUserId());// 用户ID
            userAccountOpHis.setChangeBalance(balance);// 消费
            userAccountOpHis.setOldBalance(oldBalance);// 期初余额
            userAccountOpHis.setNowBalance(endBalance);// 期末余额
            userAccountOpHis.setResume("通讯盒：" + traderecords.getTerminalNo());
            userAccountOpJnlService.insert(userAccountOpHis);

            // ==========================账户历史变动表===================================

            // 7、判断交易是否支付，没有则直接扣款
            userInfo.setAccountBalance(endBalance);// 进行扣款
            // user.setUpdateTime(new Date());
            userAccountInfoService.updateByPrimaryKeySelective(userInfo);


            return new ApiResult( ApiResultConstant.SUCCESS);
//
//            logger.info(LogUtils.build("appPay", "app手动支付", "APP支付手动扣款成功。transacSeq：" + transacSeq
//                    + ",UserId:" + userInfo.getUserId() + ",余额变动[" + oldBalance + "->" + endBalance + "]"));
//
//            // 9、下发2008，通知车道抬杠，等待1008、1009
//            BoxResponse response2008 = BoxResUtils.build2008(String.valueOf(traderecords.getTerminalNo()),
//                    traderecords.getTransNo(), PayResult.成功, PayType.BOX_APP支付, PayChannelCode.自有钱包, null);
//            sendBoxSocket.pubsubRes2BoxServer(response2008);
//
//            resqMap.put("mess", "交易成功");
//            resqMap.put("state", "1");// 交易成功
        }

        return new ApiResult( ApiResultConstant.APP_ORDER_FAILS);

    }

    /**
     * 获取通行记录信息
     * 需要优化，不可以从总表查询
     * @return
     */
    @ResponseBody
    @ApiOperation(value="获取通行记录信息",notes="根据用户ID可分页查通行记费录信息")
    @RequestMapping(value = "/findByDrivingRecord", method = RequestMethod.POST)
    @ApiImplicitParams( value = {
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "Long", required = true, value = "用户ID"),
            @ApiImplicitParam(paramType = "query", name = "plate", dataType = "String", required = true, value = "车牌号"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", dataType = "Integer",
                    required = true,defaultValue = "1", value = "每页条数"),
            @ApiImplicitParam(paramType = "query", name = "pageIndex", dataType = "Integer",
                    required = true,defaultValue = "5",  value = "第几页"),
            @ApiImplicitParam(paramType = "query", name = "beginDate", dataType = "String", required = false, value = "开始日期 YYYY-MM-DD"),
            @ApiImplicitParam(paramType = "query", name = "endDate", dataType = "String", required = false, value = "结束日期 YYYY-MM-DD"),
            @ApiImplicitParam(paramType = "query", name = "search", dataType = "String", required = false, value = "订单号关键字查询")
    })
    public Object findByDrivingRecord(HttpServletRequest request,
                                        @RequestParam(required = true, defaultValue = "0", value = "userId") Long userId,
                                        @RequestParam(required = true, defaultValue = "", value = "plate") String plate,
                                        @RequestParam(required = true, defaultValue = "0", value = "pageSize") int pageSize,
                                        @RequestParam(required = true, defaultValue = "5", value = "pageIndex") int pageIndex,
                                        @RequestParam(required = false, defaultValue = "", value = "beginDate") String beginDate,
                                        @RequestParam(required = false, defaultValue = "", value = "endDate") String endDate,
                                        @RequestParam(required = false, defaultValue = "", value = "search") String search ){

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        ItcsTransJnlExample itcsTransJnlExample = new ItcsTransJnlExample();

        ItcsTransJnlExample.Criteria criteria = itcsTransJnlExample.createCriteria();
        criteria.andUserIdEqualTo( userId );

        //模糊查询
        if(StringUtils.isNotEmpty( search )) {
            search = "%"+search+"%";
            criteria.andTransNoLike(search);
        }

        //车牌
        if(StringUtils.isNotEmpty( plate )) {
            criteria.andCarPlateEqualTo(plate);
        }

        //日期筛选
        if(StringUtils.isNotEmpty( beginDate )) {
            if(StringUtils.isNotEmpty( endDate )){
                criteria.andCreateTimeBetween(
                        DateUtils.parseDate(beginDate,"yyyy-MM-dd")
                        ,DateUtils.parseDate(endDate,"yyyy-MM-dd"));
            }else {
                criteria.andCreateTimeEqualTo(DateUtils.parseDate(beginDate,"yyyy-MM-dd"));
            }
        }
        else{
            //如果不传则查询一周内的通行记录
            criteria.andCreateTimeBetween(
                    DateUtils.getDate(DateUtils.getAfterDay(-7),"yyyy-MM-dd")
                    ,
                    DateUtils.getDate("yyyy-MM-dd"));
        }

        //排序
        itcsTransJnlExample.setOrderByClause("toll_time desc");


        //分页查询
        List<ItcsTransJnl> itcsTransJnls = itcsTransJnlService.selectByExampleForStartPage(itcsTransJnlExample,pageIndex,pageSize);

        Integer total = itcsTransJnlService.countByExample(itcsTransJnlExample);

        //填充收费站名称
        if(null != total && total>0){
            List<ItcsPlazaInfo> itcsPlazaInfos = itcsPlazaInfoService.selectOwnerPlazaByCache(DateUtils.dateFormatNow( "YYYYMMDDHH" ));

            for (ItcsTransJnl itcsTransJnl:itcsTransJnls){
                for (ItcsPlazaInfo itcsPlazaInfo:itcsPlazaInfos){
                    if(null != itcsTransJnl.getiTollPlazaId() &&  itcsTransJnl.getiTollPlazaId().equals(itcsPlazaInfo.getTollPlazaId())){
                        itcsTransJnl.setiTollPlazaName(itcsPlazaInfo.getName());
                    }
                    if(null != itcsTransJnl.geteTollPlazaId() &&  itcsTransJnl.geteTollPlazaId().equals(itcsPlazaInfo.getTollPlazaId())){
                        itcsTransJnl.seteTollPlazaName(itcsPlazaInfo.getName());
                    }
                }
            }
        }


        return new ApiResult( ApiResultConstant.SUCCESS,itcsTransJnls,total);
    }




    /**
     * 获取通行记录信息
     * 需要优化，不可以从总表查询
     * @return
     */
    @ResponseBody
    @ApiOperation(value="通过车牌获取通行记录信息",notes="根据用户ID和车牌号可分页查通行记费录信息")
    @RequestMapping(value = "/findByDrivingPlate", method = RequestMethod.POST)
    @ApiImplicitParams( value = {
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "Long", required = true, value = "用户ID"),
            @ApiImplicitParam(paramType = "query", name = "plate", dataType = "String", required = false, value = "车牌号"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", dataType = "Integer",
                    required = true,defaultValue = "1", value = "每页条数"),
            @ApiImplicitParam(paramType = "query", name = "pageIndex", dataType = "Integer",
                    required = true,defaultValue = "5",  value = "第几页"),
            @ApiImplicitParam(paramType = "query", name = "beginDate", dataType = "String", required = false, value = "开始日期 YYYY-MM-DD"),
            @ApiImplicitParam(paramType = "query", name = "endDate", dataType = "String", required = false, value = "结束日期 YYYY-MM-DD"),
            @ApiImplicitParam(paramType = "query", name = "search", dataType = "String", required = false, value = "订单号关键字查询")
    })
    public Object findByDrivingPlate(HttpServletRequest request,
                                      @RequestParam(required = true, defaultValue = "0", value = "userId") Long userId,
                                     @RequestParam(required = false, defaultValue = "", value = "plate") String plate,
                                      @RequestParam(required = true, defaultValue = "0", value = "pageSize") int pageSize,
                                      @RequestParam(required = true, defaultValue = "5", value = "pageIndex") int pageIndex,
                                      @RequestParam(required = false, defaultValue = "", value = "beginDate") String beginDate,
                                      @RequestParam(required = false, defaultValue = "", value = "endDate") String endDate,
                                      @RequestParam(required = false, defaultValue = "", value = "search") String search){

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        ItcsTransJnlExample itcsTransJnlExample = new ItcsTransJnlExample();

        ItcsTransJnlExample.Criteria criteria = itcsTransJnlExample.createCriteria();
        criteria.andUserIdEqualTo( userId );

        //模糊查询订单号
        if(StringUtils.isNotEmpty( search )) {
            search = "%"+search+"%";
            criteria.andTransNoLike(search);
        }


        //车牌
        if(StringUtils.isNotEmpty( plate )) {
            criteria.andCarPlateEqualTo(plate);
        }

        //日期筛选
        if(StringUtils.isNotEmpty( beginDate )) {
            if(StringUtils.isNotEmpty( endDate )){
                criteria.andCreateTimeBetween(
                        DateUtils.parseDate(beginDate,"yyyy-MM-dd")
                        ,DateUtils.parseDate(endDate,"yyyy-MM-dd"));
            }else {
                criteria.andCreateTimeEqualTo(DateUtils.parseDate(beginDate,"yyyy-MM-dd"));
            }
        }
        else{
            //如果不传则查询一周内的通行记录
            criteria.andCreateTimeBetween(
                    DateUtils.getDate(DateUtils.getAfterDay(-7),"yyyy-MM-dd")
                    ,
                    DateUtils.getDate("yyyy-MM-dd"));
        }

        //排序
        itcsTransJnlExample.setOrderByClause("toll_time desc");

        //分页查询
        List<ItcsTransJnl> itcsTransJnls = itcsTransJnlService.selectByExampleForStartPage(itcsTransJnlExample,pageIndex,pageSize);

        Integer total = itcsTransJnlService.countByExample(itcsTransJnlExample);

        //填充收费站名称
        if(null != total && total>0){
            List<ItcsPlazaInfo> itcsPlazaInfos = itcsPlazaInfoService.selectOwnerPlazaByCache(DateUtils.dateFormatNow( "YYYYMMDDHH" ));

            for (ItcsTransJnl itcsTransJnl:itcsTransJnls){
                for (ItcsPlazaInfo itcsPlazaInfo:itcsPlazaInfos){
                    if(null != itcsTransJnl.getiTollPlazaId() &&  itcsTransJnl.getiTollPlazaId().equals(itcsPlazaInfo.getTollPlazaId())){
                        itcsTransJnl.setiTollPlazaName(itcsPlazaInfo.getName());
                    }
                    if(null != itcsTransJnl.geteTollPlazaId() &&  itcsTransJnl.geteTollPlazaId().equals(itcsPlazaInfo.getTollPlazaId())){
                        itcsTransJnl.seteTollPlazaName(itcsPlazaInfo.getName());
                    }
                }
            }
        }


        return new ApiResult( ApiResultConstant.SUCCESS,itcsTransJnls,total);
    }



    /**
     * 获取通行记录信息根据车牌汇总
     * 需要优化，不可以从总表查询
     * @return
     */
    @ResponseBody
    @ApiOperation(value="获取通行记录信息根据车牌汇总",notes="获取通行记录信息根据车牌汇总")
    @RequestMapping(value = "/totalPlateTollFare", method = RequestMethod.POST)
    @ApiImplicitParams( value = {
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "Long", required = true, value = "用户ID"),
            @ApiImplicitParam(paramType = "query", name = "plate", dataType = "String", required = true, value = "车牌号")
    })
    public Object findByDrivingRecord(HttpServletRequest request,
                                      @RequestParam(required = false, defaultValue = "0", value = "userId") Long userId,
                                      @RequestParam(required = false, defaultValue = "", value = "plate") String plate){

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        //根据车牌号查询
        if(StringUtils.isEmpty( plate )) {
            return new ApiResult(ApiResultConstant.FAILED);
        }

        ItcsTransJnl itcsTransJnl = itcsTransJnlService.totalPlateTollFare(userId,plate);

        //重新格式化
        ItcsTransTotalPlateJnl itcsTransTotalPlateJnl = new ItcsTransTotalPlateJnl();
        if(null != itcsTransTotalPlateJnl){
            itcsTransTotalPlateJnl.setAmount(itcsTransJnl.getTollFare());
            itcsTransTotalPlateJnl.setCount(itcsTransJnl.getTerminalNo().intValue());
            itcsTransTotalPlateJnl.setPlate(plate);
        }

        return new ApiResult( ApiResultConstant.SUCCESS,itcsTransTotalPlateJnl);
    }

}